package top.korori.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import top.korori.common.utils.RedisCache;
import top.korori.constant.CacheConstant;
import top.korori.entity.SvUserArea;
import top.korori.entity.res.SvUserAreaTreeRes;
import top.korori.mapper.SvUserAreaMapper;
import top.korori.service.ISvUserAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * 前台用户所在地地区库 服务实现类
 * 
 *
 * @author korori
 *
 */
@Service
public class SvUserAreaServiceImpl extends ServiceImpl<SvUserAreaMapper, SvUserArea> implements ISvUserAreaService {

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<SvUserAreaTreeRes> tree() {

        List<SvUserAreaTreeRes> cacheData  =  redisCache.get(CacheConstant.SV_USER_AREA_TREE);
        if (ObjUtil.isNotEmpty(cacheData)){
            return cacheData;
        }

        List<SvUserArea> list = this.list();

        List<SvUserAreaTreeRes> userAreaTree = BeanUtil.copyToList(list, SvUserAreaTreeRes.class);

        List<SvUserAreaTreeRes> parentList = userAreaTree.stream()
                .filter(item -> ObjUtil.equals(item.getParentId(), 0))
                .collect(Collectors.toList());

        for (SvUserAreaTreeRes svUserAreaTreeRes : parentList) {
            List<SvUserAreaTreeRes> collect = userAreaTree.stream()
                    .filter(item -> ObjUtil.equals(item.getParentId(), svUserAreaTreeRes.getAreaId()))
                    .collect(Collectors.toList());
            svUserAreaTreeRes.setChildren(collect);
        }

        redisCache.set(CacheConstant.SV_USER_AREA_TREE,parentList);

        return parentList;
    }

    @Override
    public Boolean isExistArea(Integer provinceId, Integer cityId) {
        List<SvUserAreaTreeRes> tree = tree();
        List<SvUserAreaTreeRes> provinces = tree.stream()
                .filter(province -> ObjUtil.equals(provinceId, province.getAreaId()))
                .collect(Collectors.toList());
        if (ObjUtil.isEmpty(provinces)){
            return false;
        }

        SvUserAreaTreeRes svUserAreaTreeRes = provinces.get(0);

        List<SvUserAreaTreeRes> citys = svUserAreaTreeRes.getChildren().stream()
                .filter(city -> ObjUtil.equals(provinceId, svUserAreaTreeRes.getAreaId()))
                .collect(Collectors.toList());

        return !ObjUtil.isEmpty(citys);
    }
}

























